import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, PanResponder, Animated, Dimensions, Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import AsyncStorage from '@react-native-async-storage/async-storage';

type RootStackParamList = {
  Denglu: undefined;
  Zhuce: undefined;
  Shouzhao: undefined;
  Youzhao: undefined;
  MainTabs: undefined;
  Daohang: undefined;
  Xuanze: undefined;
};

type NavigationProp = NativeStackNavigationProp<RootStackParamList, 'Denglu'>;

const LoginScreen = () => {
  const navigation = useNavigation<NavigationProp>();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [isFormValid, setIsFormValid] = useState(false);
  const [isSliderVerified, setIsSliderVerified] = useState(false);
  const [accountError, setAccountError] = useState('');
  const [isCheckingUsername, setIsCheckingUsername] = useState(false);
  const [usernameExists, setUsernameExists] = useState(true);

  // 验证账号格式：必须包含数字、大写字母和小写字母
  const validateUsername = (text: string) => {
    const hasNumber = /\d/.test(text);
    const hasUpperCase = /[A-Z]/.test(text);
    const hasLowerCase = /[a-z]/.test(text);
    return hasNumber && hasUpperCase && hasLowerCase;
  };

  // 验证密码格式：必须包含数字和字母
  const validatePassword = (text: string) => {
    const hasNumber = /\d/.test(text);
    const hasLetter = /[a-zA-Z]/.test(text);
    return hasNumber && hasLetter;
  };

  // 检查用户名是否存在
  const checkUsernameExists = async (text: string) => {
    if (!text) {
      setUsernameExists(true);
      return;
    }
    
    setIsCheckingUsername(true);
    try {
      const response = await fetch('http://192.168.78.1:3000/users/check-username', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username: text })
      });

      const data = await response.json();
      setUsernameExists(data.exists);
      if (!data.exists) {
        setAccountError('该账号未注册');
      } else {
        setAccountError('');
      }
    } catch (error) {
      console.error('检查用户名失败:', error);
      setUsernameExists(true);
    } finally {
      setIsCheckingUsername(false);
    }
  };

  // 监听输入变化并更新表单验证状态
  useEffect(() => {
    const isUsernameValid = validateUsername(username);
    const isPasswordValid = validatePassword(password);
    setIsFormValid(isUsernameValid && isPasswordValid && usernameExists);
  }, [username, password, usernameExists]);

  // 处理用户名输入变化
  const handleUsernameChange = (text: string) => {
    setUsername(text);
    setAccountError('');
    if (validateUsername(text)) {
      checkUsernameExists(text);
    }
  };

  const handleLogin = async () => {
    if (isFormValid) {
      try {
        // 获取用户信息
        const userInfoResponse = await fetch('http://192.168.78.1:3000/users/get-user-info', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ username })
        });

        const userInfoData = await userInfoResponse.json();
        
        if (userInfoData.code !== 200) {
          Alert.alert('错误', userInfoData.message || '获取用户信息失败');
          return;
        }

        // 存储用户信息到本地
        await AsyncStorage.setItem('name', userInfoData.data.username);
        await AsyncStorage.setItem('money', userInfoData.data.money.toString());
        
        navigation.navigate('MainTabs');
      } catch (error) {
        console.error('登录失败:', error);
        Alert.alert('错误', '网络错误，请重试');
      }
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity style={styles.backBtn} onPress={() => navigation.navigate('MainTabs')}>
          <Text style={styles.backBtnText}>{'<'}</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>登录</Text>
      </View>
      <View style={styles.form}>
        {!validateUsername(username) && username !== '' && (
          <Text style={styles.errorText}>账号必须包含数字、大写字母和小写字母</Text>
        )}
        {accountError ? <Text style={styles.errorText}>{accountError}</Text> : null}
        {isCheckingUsername && (
          <Text style={styles.checkingText}>正在检查账号...</Text>
        )}
        <TextInput 
          style={[
            styles.input, 
            (!validateUsername(username) && username !== '') || accountError ? styles.inputError : null
          ]} 
          placeholder="输入账号" 
          placeholderTextColor="#bbb"
          value={username}
          onChangeText={handleUsernameChange}
        />
        {!validatePassword(password) && password !== '' && (
          <Text style={styles.errorText}>密码必须包含数字和字母</Text>
        )}
        <TextInput 
          style={[styles.input, !validatePassword(password) && password !== '' && styles.inputError]} 
          placeholder="输入密码" 
          placeholderTextColor="#bbb" 
          secureTextEntry
          value={password}
          onChangeText={setPassword}
        />
        <View style={styles.row}>
          <TouchableOpacity onPress={() => navigation.navigate('Xuanze')}>
            <Text style={styles.linkGray}>忘记密码?</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={() => navigation.navigate('Zhuce')}>
            <Text style={styles.linkRed}>注册新账号</Text>
          </TouchableOpacity>
        </View>
        <TouchableOpacity 
          style={[styles.loginBtn, !isFormValid && styles.loginBtnDisabled]} 
          onPress={handleLogin}
          disabled={!isFormValid}
        >
          <Text style={[styles.loginBtnText, !isFormValid && styles.loginBtnTextDisabled]}>登录</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#f2f2f2',
    marginBottom: 10,
    position: 'relative',
  },
  backBtn: {
    position: 'absolute',
    left: 10,
    top: 0,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 10,
    zIndex: 1,
  },
  backBtnText: {
    fontSize: 22,
    color: '#333',
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  form: {
    paddingHorizontal: 20,
    flex: 1,
    top:50,
  },
  input: {
    height: 40,
    backgroundColor: '#f5f5f5',
    borderRadius: 5,
    paddingHorizontal: 10,
    marginBottom: 15,
    fontSize: 14,
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 30,
  },
  linkGray: {
    color: '#bbb',
    fontSize: 13,
    left:15,
  },
  linkRed: {
    color: '#d32f2f',
    fontSize: 13,
    right:15,
  },
  inputError: {
    borderColor: '#d32f2f',
    borderWidth: 1,
  },
  errorText: {
    color: '#d32f2f',
    fontSize: 12,
    marginBottom: 5,
    marginLeft: 5,
  },
  loginBtnDisabled: {
    backgroundColor: '#cccccc',
  },
  loginBtnTextDisabled: {
    color: '#666666',
  },
  loginBtn: {
    backgroundColor: '#d32f2f',
    borderRadius: 5,
    height: 45,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10,
  },
  loginBtnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  checkingText: {
    color: '#bbb',
    fontSize: 12,
    marginBottom: 5,
    marginLeft: 5,
  },
});

export default LoginScreen;
